/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.session;

import com.inspur.edp.bef.core.session.distributed.close.SessionRelationBizCacheManger;
import java.util.Set;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SessionCacheCheckInSys implements Job {

  private static Logger logger = LoggerFactory.getLogger(SessionCacheCheckInSys.class);

  static void startCleanerScheduler() {
    boolean sys = FuncSessionUtil.msuEnabled("Sys");
    boolean redis = FuncSessionUtil.redisEnabled();
    if (sys && redis) {
      FuncSessionUtil
          .startScheduler(SessionCacheCheckInSys.class, "SessionCacheCheckInSys", 10, 1);
    } else {
      logger.warn("SessionCacheCheckInSys定时任务未启动:sys-" + sys + ";redis-" + redis);
    }
  }

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    try {
      cleanTokenInRedis();
    } catch (Throwable r) {
      logger.error("sys定时任务执行失败一次", r);
    }
  }

  private static synchronized void cleanTokenInRedis() {
    Set<String> tokenIds = SessionRelationBizCacheManger.getInstance().getHashKeySet();
    if (tokenIds == null || tokenIds.isEmpty()) {
      return;
    }
    int failedCount = 0;
    Throwable lastError = null;
    for (String tokenId : tokenIds) {
      try {
        if (FuncSessionUtil.isTokenExpired(tokenId)) {
          SessionRelationBizCacheManger.getInstance().evict(tokenId);
        }
      } catch (Throwable t) {
        failedCount++;
        lastError = t;
      }
    }
    if (failedCount > 0) {
      logger.error("sys定时任务内部失败次数" + failedCount, lastError);
    }
  }
}
